package com.ruoyi.staff.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.staff.domain.StaffContract;
import com.ruoyi.staff.service.IStaffContractService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 员工合同Controller
 * 
 * @author bzs
 * @date 2021-06-28
 */
@Controller
@RequestMapping("/staff/contract")
public class StaffContractController extends BaseController
{

    private static final Logger log = LoggerFactory.getLogger(StaffContractController.class);

    private String prefix = "staff/contract";

    @Autowired
    private IStaffContractService staffContractService;

    @RequiresPermissions("staff:contract:view")
    @GetMapping()
    public String contract()
    {
        return prefix + "/contract";
    }

    /**
     * 上传合同附件
     */
    @PostMapping("/importAttachment")
    @ResponseBody
    public AjaxResult importAttachment(MultipartFile file,String stfIds){
        StaffContract contract = staffContractService.selectStaffContractById(Long.valueOf(stfIds));
        String oldFileStr = contract.getStfContractPath();
        oldFileStr = oldFileStr.replaceAll("/profile", Global.getProfile());
        File oldFile = new File(oldFileStr);
        if(oldFile.exists()){
            oldFile.delete();
        }else{
            logger.info("文件不存在");
        }
        if(!file.isEmpty()){
                try {
                    //取得合同附件地址
                    String attach = FileUploadUtils.upload(Global.getAttachPath(),file);

                    //将合同附件地址放到合同的地址属性中
                    contract.setStfContractPath(attach);
                    staffContractService.updateStaffContract(contract);

                } catch (IOException e) {
                    e.printStackTrace();
                    return AjaxResult.error("上传失败，请查看后台日志");
                }
            }
            return AjaxResult.success();
    }

    /**
     * 下载合同附件
     */
    @PostMapping("/exportAttachment")
    @ResponseBody
    public AjaxResult exportAttachment(String stfId, HttpServletRequest request, HttpServletResponse response){
        //1，根据工号去库里查询文件地址
        StaffContract staffContract =new StaffContract();
        staffContract.setStfId(Long.valueOf(stfId));
        List<StaffContract> listContract = staffContractService.selectStaffContractList(staffContract);
        staffContract = listContract.get(0);
        String filePath = staffContract.getStfContractPath();
        filePath = filePath.replaceAll("/profile", Global.getProfile());
        return AjaxResult.success("success",filePath);
    }

    @GetMapping("/downloadAttachment")
    @ResponseBody
    public void downloadAttachment(String downloadPath,HttpServletResponse response){
        try {
            //2,根据文件地址下载文件
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            //writeBytes方法需用在get请求中
            FileUtils.writeBytes(downloadPath,response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 查询员工合同列表
     */
    @RequiresPermissions("staff:contract:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(StaffContract staffContract)
    {
        startPage();
        List<StaffContract> list = staffContractService.selectStaffContractList(staffContract);
        return getDataTable(list);
    }

    /**
     * 导出员工合同列表
     */
    @RequiresPermissions("staff:contract:export")
    @Log(title = "员工合同", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(String ids)
    {
        String[] stfIds = Convert.toStrArray(ids);
        List<StaffContract> list = staffContractService.selectStaffContractListByIds(stfIds);
        ExcelUtil<StaffContract> util = new ExcelUtil<StaffContract>(StaffContract.class);
        return util.exportExcel(list, "contract");
    }

    /**
     * 导入员工合同列表
     * */
    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("staff:contract:import")
    @PostMapping("/importExcel")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<StaffContract> util = new ExcelUtil<>(StaffContract.class);
        List<StaffContract> lists = util.importExcel(file.getInputStream());
        SysUser sysUser = ShiroUtils.getSysUser();
        //校验数据
        String res = staffContractService.validateDatas(lists);
        if (StringUtils.isNotBlank(res)){
            return AjaxResult.error(res);
        }
        String message =staffContractService.importcontractRelations(lists,updateSupport,sysUser);
        return AjaxResult.success(message);
    }

    /**
     * 导入中的下载模板
     * */
    @RequiresPermissions("staff:contract:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<StaffContract> util = new ExcelUtil<StaffContract>(StaffContract.class);
        return util.importTemplateExcel("员工合同数据");
    }

    /**
     * 新增员工合同
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存员工合同
     */
    @RequiresPermissions("staff:contract:add")
    @Log(title = "员工合同", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(StaffContract staffContract)
    {
        return toAjax(staffContractService.insertStaffContract(staffContract));
    }

    /**
     * 修改员工合同
     */
    @GetMapping("/edit/{stfId}")
    public String edit(@PathVariable("stfId") String stfId, ModelMap mmap)
    {
        StaffContract staffContract = staffContractService.selectStaffContractById(Long.valueOf(stfId));
        mmap.put("staffContract", staffContract);
        return prefix + "/edit";
    }

    /**
     * 修改保存员工合同
     */
    @RequiresPermissions("staff:contract:edit")
    @Log(title = "员工合同", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(StaffContract staffContract)
    {
        return toAjax(staffContractService.updateStaffContract(staffContract));
    }

    /**
     * 删除员工合同
     */
    @RequiresPermissions("staff:contract:remove")
    @Log(title = "员工合同", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String[] ids)
    {
        return toAjax(staffContractService.deleteStaffContractByIds(ids));
    }
}
